package com.liyongjian.xhban.api;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.liyongjian.xhban.dal.UserRepository;
import com.liyongjian.xhban.dal.UserWeixinRepository;
import com.liyongjian.xhban.dto.AjaxResponse;
import com.liyongjian.xhban.model.User;
import com.liyongjian.xhban.model.UserWeixin;
import com.liyongjian.xhban.utils.HttpUtils;
import com.liyongjian.xhban.utils.MapUtils;


@Controller
@RequestMapping("/api/user")
public class UserController extends BaseController {

    @Autowired
    private UserWeixinRepository userWeixinRepository;
    @Autowired
    private UserRepository userRepository;

    private String stringFilter(String str) {
        String regEx =
                "[^(\u2E80-\u9FFF\\w\\s`~!@#\\$%\\^&\\*\\(\\)_+-？（）——=\\[\\]{}\\|;。，、《》”：；“！……’:'\"<,>\\.?/\\\\*)]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    @Transactional
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(path = "login", method = RequestMethod.GET)
    public AjaxResponse login(HttpServletRequest request, String code, String nickName,
            String avatarUrl, HttpServletResponse response) throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        Map<String, Object> map = this.getRequestParameter(request);

        String json = HttpUtils.getJson(jscode2sessionUrl + "?appid=" + appid + "&secret="
                + appsecret + "&grant_type=authorization_code&js_code=" + code);
        Map<String, Object> jmap = (Map<String, Object>) jsonMapper.fromJson(json, Map.class);
        nickName = stringFilter(nickName);

        if (jmap.containsKey("openid")) {
            String openid = jmap.get("openid").toString();
            UserWeixin uw = userWeixinRepository.findByOpenid(openid);
            User user = null;
            if (uw == null) {
                uw = new UserWeixin();
                MapUtils.copyProperties(uw, map);
                user = new User();
                user.nickName = nickName;
                user.name = nickName;
                user.photo = avatarUrl;
                userRepository.save(user);

                uw.openid = openid;
                uw.userId = user.id;
                uw.nickName = nickName;


                if (StringUtils.isEmpty(nickName)) {
                    user.nickName = user.id.toString();
                    user.name = user.id.toString();
                    userRepository.save(user);

                    uw.nickName = user.id.toString();
                }
                userWeixinRepository.save(uw);
            } else {
                user = userRepository.findOne(uw.userId);
                user.name = nickName;
                user.photo = avatarUrl;
                userRepository.save(user);
            }
            String token = UUID.randomUUID().toString();
            this.saveCurrentUser(token, uw.userId);
            Map<String, Object> res = new HashMap<String, Object>();
            res.put("token", token);
            res.put("id", uw.userId);
            res.put("nickName", user.nickName);
            res.put("photo", user.photo);
            return ajax.setObj(res);
        } else {
            return ajax.setMsg("登入失败");
        }
    }



}
